<?php

namespace backend\controllers;

use backend\models\SendMsg;
use yii\helpers\Html;
use Yii;
use backend\models\CustomerCommuHistory;
use backend\models\CustomerContact;
use backend\models\Customer;
use backend\models\Customersearch;
use backend\models\CustomerContactSearch;
use backend\models\CustomerCommuHistorySearch;
use backend\models\UploadFormDjr;
use yii\base\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\web\Response;
use yii\widgets\ActiveForm;
use backend\models\Tags;

/**
 * CustomerController implements the CRUD actions for Customer model.
 */
class CustomerController extends Controller
{
    public $layout = 'yue-juan';

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all Customer models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new Customersearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $msgModel = new SendMsg();
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'msgModel' => $msgModel,
        ]);
    }

    /**
     * Displays a single Customer model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Customer model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Customer();

        //联系人
        $contactModel = new CustomerContact();
        $post = Yii::$app->request->post();
        $count = count(Yii::$app->request->post('CustomerContact', []));
        for ($i = 0; $i < $count; $i++) {
            $contactModels[] = clone $contactModel;
        }

        //沟通记录
        $historyModel = new CustomerCommuHistory();

        $tagModel = new Tags();

        if (Yii::$app->request->isPost) {

            if ($model->load($post) && $tagModel->load($post) && Model::loadMultiple($contactModels, $post) && $contactModel->load($post) && $historyModel->load($post) && $model->validate() && Model::validateMultiple($contactModels) && $historyModel->validate()) {
//            $model->type = $model->type ? implode(',', $model->type) : '';
                $model->type_desc = $model->type_desc ? implode(',', $model->type_desc) : '';
                $model->province = $model->province ? implode(',', $model->province) : '';
                $model->project_province = $model->project_province ? implode(',', $model->project_province) : '';
                $model->owner = Yii::$app->user->getId();
                $model->created_at = date('Y-m-d H:i:s');
                /*
                //upload image
                if ($_FILES['Customer']['tmp_name']['image']) {
                    $type = substr(strstr($_FILES['Customer']['type']['image'], '/', false), 1);
                    $model->image = "data:{$type};base64," . chunk_split(base64_encode(file_get_contents($_FILES['Customer']['tmp_name']['image'])));
                } else {
                    unset($model->image);
                }*/

                //upload file
                if ($_FILES['Customer']['name']['project_file']) {
                    $model_upload = new UploadFormDjr();
                    $model_upload->scenario = 'files';
                    $model->project_file = $model_upload->uploadFile($model, 'uploads', 'project_file', false);
                }

                //当月任务，记录首次记录机构等级为A的时间
                if ($model->company_level == 1 or $model->company_level == 5) {
                    $model->first_mark_A = date('Y-m');
                    $model->mark_A_at = date('Y-m-d H:i:s');
                }

                //自定义标签
                $tag_id = [];
                $arr_tags = explode('，', $tagModel->title);
                if (is_array($arr_tags) && count($arr_tags) > 0) {
                    foreach ($arr_tags as $item) {
                        $cloneTagModel = clone $tagModel;
                        if ($item) {
                            if (Tags::find()->where(['title' => $item, 'user_id' => Yii::$app->user->id])->one() === null) {
                                $cloneTagModel->title = $item;
                                $cloneTagModel->user_id = Yii::$app->user->id;

                                $cloneTagModel->save();
                                $tag_id[] = $cloneTagModel->id;
                            } else {
                                Yii::$app->session->addFlash('warning', $item . '标签已存在');
                            }
                        }
                    }
                }

                $model->tag = $model->tag ? array_merge($model->tag, $tag_id) : $tag_id;
                $model->tag = $model->tag ? implode(',', $model->tag) : '';

                if ($model->save()) {
                    $customer_id = $model->id;
                    //保存联系人信息
                    $count_success = 0;
                    $count_failure = 0;
                    $model_upload = new UploadFormDjr();
                    foreach ($contactModels as $key => $contactModel) {
                        $contactModel->customer_id = $customer_id;
                        //upload image
                        $model_upload = clone $model_upload;
                        $model_upload->scenario = 'default';
                        if ($_FILES['CustomerContact']['name'][$key]['image']) {
                            $contactModel->image = $model_upload->uploadImage($contactModel, 'uploads', "[$key]image", false);
                        }
                        if ($contactModel->mobile) {
                            if ($contact = $contactModel->validateMobileUnique($contactModel->mobile)) {
                                Yii::$app->session->addFlash('warning', $contact->backendUser->realname . '已经于' . $contact->created_at . '添加了此联系人' . $contactModel->contact . $contactModel->mobile);
                                continue;
                            }
                            $contactModel->owner = Yii::$app->user->id;
                            if ($contactModel->save()) {
                                $count_success++;
                            } else {
                                Yii::$app->session->addFlash('danger', serialize($model->errors));
                                $count_failure++;
                            }
                        }

                    }
                    Yii::$app->session->addFlash('info', '成功添加联系信息：' . $count_success . '，失败：' . $count_failure);

                    //保存沟通记录信息
                    $historyModel->customer_id = $customer_id;
                    if ($historyModel->history_date) {
                        if ($historyModel->save()) {
                            Yii::$app->session->addFlash('info', '沟通记录创建成功');
                        } else {
                            Yii::$app->session->addFlash('danger', '沟通记录未创建' . serialize($historyModel->getFirstErrors()));
                        }
                    }

                    Yii::$app->session->addFlash('info', '信息创建成功');
                    return $this->redirect(['index']);
//                    return $this->redirect(Yii::$app->request->referrer);
                } else {
                    Yii::$app->session->setFlash('danger', serialize($model->getErrors()));
                    return $this->redirect(Yii::$app->request->referrer);
                }

            } else {
                Yii::$app->session->addFlash('danger', serialize($model->getFirstErrors()));
                Yii::$app->session->addFlash('danger', serialize($contactModel->getFirstErrors()));
                Yii::$app->session->addFlash('danger', serialize($historyModel->getFirstErrors()));
                return $this->redirect(Yii::$app->request->referrer);
            }
        } else {
            $model->history_date = date('Y-m-d');
            $model->type = 0;
            $model->company_level = 0;
            $model->review_level = 0;

            return $this->render('create', [
                'model' => $model,
                'contactModel' => $contactModel,
                'historyModel' => $historyModel,
                'tagModel' => $tagModel,
            ]);
        }

    }

    /**
     * Updates an existing Customer model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $post = Yii::$app->request->post();
        //联系人
        $contactModel = new CustomerContact();
        $count = count(Yii::$app->request->post('CustomerContact', []));
        for ($i = 0; $i < $count; $i++) {
            $contactModels[] = clone $contactModel;
        }
        //沟通记录
        $historyModel = new CustomerCommuHistory();

//         * AJAX验证,给出错误提示
//        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
//            Yii::$app->response->format = Response::FORMAT_JSON;
//            return ActiveForm::validate($model);
//        }
        $tagModel = new Tags();
        if (Yii::$app->request->isPost) {

            if ($model->load($post) && $tagModel->load($post) && $contactModel->load($post) && $historyModel->load($post) && Model::loadMultiple($contactModels, $post) && $model->validate() && $contactModel->validate() && Model::validateMultiple($contactModels) && $historyModel->validate()) {
//            $model->type = $model->type ? implode(',', $model->type) : '';
                $model->type_desc = $model->type_desc ? implode(',', $model->type_desc) : '';
                $model->province = $model->province ? implode(',', $model->province) : '';

                $model->project_province = $model->project_province ? implode(',', $model->project_province) : '';
                //upload file
                $model_upload = new UploadFormDjr();
                $model_upload->scenario = 'files';
                $model->project_file = $model_upload->uploadFile($model, 'uploads', 'project_file', false);
//                Yii::$app->session->addFlash('danger', serialize($model->project_file) . 'error');
                if ($model->project_file == false) {
                    unset($model->project_file);
                }

                //当月任务，记录首次记录机构等级为A的时间
                if (($model->company_level == 1 or $model->company_level == 5) and $model->first_mark_A == '') {
                    $model->first_mark_A = date('Y-m');
                    $model->mark_A_at = date('Y-m-d H:i:s');
                }

                //自定义标签
                $tag_id = [];
                $arr_tags = explode('，', $tagModel->title);
                if (is_array($arr_tags) && count($arr_tags) > 0) {
                    foreach ($arr_tags as $item) {
                        $cloneTagModel = clone $tagModel;
                        if ($item) {
                            if (Tags::find()->where(['title' => $item, 'user_id' => Yii::$app->user->id])->one() === null) {
                                $cloneTagModel->title = $item;
                                $cloneTagModel->user_id = Yii::$app->user->id;

                                $cloneTagModel->save();
                                $tag_id[] = $cloneTagModel->id;
                            } else {
                                Yii::$app->session->addFlash('warning', $item . '标签已存在');
                            }
                        }
                    }
                }

                $model->tag = $model->tag ? array_merge($model->tag, $tag_id) : $tag_id;
                $model->tag = $model->tag ? implode(',', $model->tag) : '';
                if ($model->save()) {

                    $customer_id = $id;
                    //保存联系人信息
                    $count_success = 0;
                    $count_failure = 0;
                    $model_upload = new UploadFormDjr();
                    foreach ($contactModels as $key => $contactModel) {
                        $contactModel->customer_id = $customer_id;
                        //upload image
                        $model_upload = clone $model_upload;
                        $model_upload->scenario = 'default';
                        if ($_FILES['CustomerContact']['name'][$key]['image']) {
                            $contactModel->image = $model_upload->uploadImage($contactModel, 'uploads', "[$key]image", false);
                        }
                        if ($contactModel->mobile) {

                            if ($contact = $contactModel->validateMobileUnique($contactModel->mobile)) {
                                Yii::$app->session->addFlash('warning', $contact->backendUser->realname . '已经于' . $contact->created_at . '添加了此联系人' . $contactModel->contact . $contactModel->mobile);
                                continue;
                            }
                            $contactModel->owner = Yii::$app->user->id;
                            if ($contactModel->save()) {
                                $count_success++;
                            } else {
                                Yii::$app->session->addFlash('danger', '1' . serialize($model->errors));
                                $count_failure++;
                            }
                        }
                    }
                    Yii::$app->session->addFlash('info', '成功添加联系信息：' . $count_success . '，失败：' . $count_failure);

                    //保存沟通记录信息
                    $historyModel->customer_id = $customer_id;
                    if ($historyModel->history_date) {
                        if ($historyModel->save()) {
                            Yii::$app->session->addFlash('info', '沟通记录创建成功');
                        } else {
                            Yii::$app->session->addFlash('danger', '沟通记录创建失败' . serialize($historyModel->getFirstErrors()));
                        }
                    }
                    Yii::$app->session->setFlash('info', '信息修改成功');
//                    return $this->redirect(['index']);
                    return $this->redirect(Yii::$app->request->referrer);

                } else {
                    Yii::$app->session->addFlash('danger', serialize($model->getFirstErrors()));
                    return $this->redirect(['update', 'id' => $model->id]);
                }

            } else {
                $baseModel = new Model();
                Yii::$app->session->addFlash('danger', serialize($model->getErrors()) . serialize($contactModel->getErrors()) . serialize($historyModel->getErrors()));
                return $this->redirect(['update', 'id' => $model->id]);
            }

        } else {
//            $model->type = explode(',', $model->type);
            $model->type_desc = explode(',', $model->type_desc);
            $model->province = explode(',', $model->province);
            $model->project_province = explode(',', $model->project_province);
            $model->tag = explode(',', $model->tag);
            $model->history_date = date('Y-m-d');
            //联系人
            $contactSearchModel = new CustomerContactSearch();
            $contactSearchModel->customer_id = $id;
            $contactDataProvider = $contactSearchModel->search(Yii::$app->request->queryParams);
            //沟通记录
            $historySearchModel = new CustomerCommuHistorySearch();
            $historySearchModel->customer_id = $id;
            $historyDataProvider = $historySearchModel->search(Yii::$app->request->queryParams);

            return $this->render('update', [
                'model' => $model,
                'contactModel' => $contactModel,
                'historyModel' => $historyModel,

                'contactSearchModel' => $contactSearchModel,
                'contactDataProvider' => $contactDataProvider,

                'historySearchModel' => $historySearchModel,
                'historyDataProvider' => $historyDataProvider,
                'tagModel' => $tagModel,
            ]);
        }
    }

    public function actionCompanyUnique()
    {
        $post = Yii::$app->request->post();
        return Customer::find()->where(['company' => $post['company']])->exists();
    }

    /**
     * Deletes an existing Customer model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        if ($model->owner == Yii::$app->user->id) {
            $model->delete();
            CustomerContact::deleteAll(['customer_id' => $id]);
        } else {
            Yii::$app->session->setFlash('danger', '只能删除自己创建的记录哦！');
        }


        return $this->redirect(Yii::$app->request->referrer);
    }

    /**
     * Finds the Customer model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return Customer the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Customer::findOne($id)) !== null) {

            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    public function actionSendMsg()
    {
        $post = Yii::$app->request->post();
        $sendMsgModel = new SendMsg();
        if ($sendMsgModel->load($post)) {
            foreach (explode(',', $sendMsgModel->mobile) as $customer_id) {
                $contacts = CustomerContact::find()->where(['customer_id' => $customer_id])->asArray()->all();
                if (is_array($contacts) && count($contacts) > 0) {
                    foreach ($contacts as $contact) {
                        $model = clone $sendMsgModel;
                        $values = [
                            'mobile' => $contact['mobile'],
                            'title' => mb_strcut($sendMsgModel->content, 0, 30),
                            'content' => $sendMsgModel->content,
                            'user_id' => Yii::$app->user->id,
                        ];
                        $model->attributes = $values;
                        if ($result = Yii::$app->sendmsg->send($contact['mobile'], $sendMsgModel->content) <= 0) {
                            $model->status = 0;
                            $model->result = $result;
                        }
                        if ($model->save() == false) {
                            Yii::$app->session->addFlash('danger', serialize($model->getFirstErrors()));
                        }

                    }
                }
            }
        }

        Yii::$app->session->addFlash('info', '发送完成' . Html::a('查看发送结果', ['/send-msg/index']));
        return $this->redirect(Yii::$app->request->referrer);

    }
}
